﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace scmsByAspdNet.cotro.student {
  /// <summary>
  /// getAllCourseScore 的摘要说明
  /// </summary>
  public class getAllCourseScore : IHttpHandler {

    public void ProcessRequest(HttpContext context) {
      context.Response.ContentType = "text/plain";

      //获取参数
      string stu_id = context.Request["stu_id"];
      //数据库
      SqlConnection conn = new SqlConnection("Data Source=106.54.69.143;database=scms;uid=sa;pwd=Aspdotnet666");
      conn.Open();

      SqlCommand sql_rows = new SqlCommand($"SELECT sc.id,sc.title,scs.daily_grade,scs.terminal_grade,scs.ultimate_grade FROM sc_student ss,sc_cour_stu scs,sc_course sc WHERE ss.id={stu_id} AND ss.id=scs.stu_id AND scs.cour_id=sc.id AND scs.submit_flag=0", conn);
      string rows = "[";
      SqlDataReader reader = sql_rows.ExecuteReader();
      for (; reader.Read();) {
        rows += $"{{\"cour_id\":\"{reader[0].ToString()}\",\"cour_title\":\"{reader[1].ToString()}\",\"daily_grade\":\"{reader[2].ToString()}\",\"terminal_grade\":\"{reader[3].ToString()}\",\"ultimate_grade\":\"{reader[4].ToString()}\"}},";
      }
      rows = rows.Substring(0, rows.Length - 1);
      rows += "]";
      reader.Close();
      //获取行数-----
      SqlCommand sql_total = new SqlCommand($"SELECT count(sc.id) FROM sc_student ss,sc_cour_stu scs,sc_course sc WHERE ss.id={stu_id} AND ss.id=scs.stu_id AND scs.cour_id=sc.id AND scs.submit_flag=0", conn);
      string total = "";
      reader = sql_total.ExecuteReader();
      if (reader.Read()) {
        total = reader[0].ToString();
      }
      else {
        total = "0";
      }
      reader.Close();
      conn.Close();
      //返回数据
      string ret = "{" +
        "\"total\":\"" + total + "\"," +
        "\"rows\":" + rows + "" +
        "}";
      System.Console.WriteLine(ret);
      context.Response.StatusCode = 200;
      context.Response.Write(ret);
    }

    public bool IsReusable {
      get {
        return false;
      }
    }
  }
}